package com.powernode.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.HashMap;
import java.util.Map;

/**
 * JWT令牌工具类
 */
public class JWTUtils {

    public static final String SECRET = "js(6G4b134l&1kadsf91a2345*6j";

    /**
     * 生成JWT令牌
     * @param dataJsonStr
     * @return
     */
    public static String createJwt(String dataJsonStr) {
        Map<String,Object> headers = new HashMap<>();
        headers.put("alg","HS256");
        headers.put("typ","JWT");
        return JWT.create()
                .withHeader(headers)
                .withClaim("user", dataJsonStr)
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 验证JWT令牌
     * @param jwt
     * @return
     */
    public static Boolean verifyJwt(String jwt) {
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(jwt);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 解析JWT获取载体数据
     * @param jwt
     * @return
     */
    public static String parseJwt(String jwt) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(jwt);
            Claim claim = decodedJWT.getClaim("user");
            return claim.asString();
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (JWTVerificationException e) {
            throw new RuntimeException(e);
        }
    }

}
